package service

import (
	"context"
	"fmt"
	"gitee.com/hxchjm/go-admin/internal/dao"
	"gitee.com/hxchjm/go-admin/internal/models"
	"gitee.com/hxchjm/go-admin/pkg/cas"
	"gitee.com/hxchjm/go-admin/pkg/jwtauth"
	"github.com/hxchjm/log"
	"github.com/jinzhu/copier"
)

type Role struct {
}

func (r Role) GetPage(ctx context.Context, req *models.ReqRoleGetPage) (rsp *models.RspRoleGetPage, err error) {
	res, cnt, err := dao.SysRole{}.GetList(ctx, req)
	if err != nil {
		return
	}
	rsp = &models.RspRoleGetPage{
		Total: int(cnt),
		Page:  req.Page,
		Size:  req.Size,
	}
	for _, v := range res {
		rsp.List = append(rsp.List, v.SysRole)
	}
	return
}
func (r Role) Get(ctx context.Context, req *models.ReqRoleGet) (rsp interface{}, err error) {
	rsp, err = dao.SysRole{SysRole: models.SysRole{RoleId: req.Id}}.Get(ctx)
	if err != nil {
		return nil, err
	}
	return
}
func (r Role) Insert(ctx context.Context, req *models.ReqRoleInsert) (rsp any, err error) {
	if err = (dao.SysRole{SysRole: *req}).Insert(ctx); err != nil {
		return
	}
	if err = cas.GetIns().LoadPolicy(); err != nil {
		log.Errorf(ctx, "load policy err (%+v),req(%+v)", err, req)
		return
	}
	return
}
func (r Role) Update(ctx context.Context, req *models.ReqRoleUpdate) (rsp any, err error) {
	sr := dao.SysRole{}
	_ = copier.Copy(&sr, req)
	if err = sr.Update(ctx); err != nil {
		return
	}
	if err = cas.GetIns().LoadPolicy(); err != nil {
		log.Errorf(ctx, "load policy err (%+v),req(%+v)", err, req)
		return
	}
	return
}
func (r Role) Delete(ctx context.Context, req *models.ReqRoleDelete) (rsp any, err error) {
	if err = (dao.SysRole{}).Delete(ctx, req.Ids); err != nil {
		return
	}
	return
}

// UpdateDataScope 更新角色数据权限
// @Summary 更新角色数据权限
// @Description 获取JSON
// @Tags 角色/Role
// @Accept  application/json
// @Product application/json
// @Param data body dto.RoleDataScopeReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/role-status/{id} [put]
// @Security Bearer
func (r Role) UpdateDataScope(ctx context.Context, req *models.ReqUpdateScope) (any, error) {
	var err error
	data := &models.SysRole{
		RoleId:    req.RoleId,
		DataScope: req.DataScope,
		DeptIds:   req.DeptIds,
	}

	data.UpdateBy = jwtauth.GetClaims(ctx).UID
	err = dao.SysRole{SysRole: models.SysRole{RoleId: req.RoleId, DeptIds: req.DeptIds, DataScope: req.DataScope}}.
		UpdateDataScope(ctx)
	if err != nil {
		log.Errorf(ctx, fmt.Sprintf("更新角色数据权限失败！错误详情：%+v", err))
		return nil, err
	}
	return nil, nil
}
